package com.hsq.ndmall.common.holder;

import cn.hutool.json.JSONObject;
import com.hsq.ndmall.common.dto.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 黄四清
 * @version 1.0.0
 * @ClassName LoginUser.java
 * @Description TODO 从网关的全局过滤器获得用户信息
 * @createTime 2021年09月01日 10:42:00
 */
@Component
public class LoginUserHolder {

    /**
     * 从header中获取用户信息
     *
     * @return
     */
    public UserDto getCurrentUser() {
        // 从全局请求拿到上下文。
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取请求
        HttpServletRequest request = requestAttributes.getRequest();
        String userStr = request.getHeader("user");
        UserDto userDto = new UserDto();
        JSONObject userJsonObject = new JSONObject(userStr);
        userDto.setId(userJsonObject.getLong("id"));
        return userDto;
    }
}
